package elitech.vietnam.myfashion;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.gson.Gson;

import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.dialog.MyDialogHandler;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Member;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.utilities.Tracker;
import elitech.vietnam.myfashion.utilities.Utilities;
import elitech.vietnam.myfashion.wsclient.Service;

public class SplashScreen extends Activity {

	public static boolean		loadingCompleted					= false;

	GoogleCloudMessaging		gcm									= null;
	// private ImageView splash_imageview;
	private ProgressBar			splash_progressbar;
	private Animation			anim;
	private TextView			txtStatus;

	boolean						loaded								= false;

	// /////////////////////////////Hung-Auto update////////////////////////////
	public final static String	UNIQUE_DEVICE_ID					= "UNIQUE_DEVICE_ID";
	public static final String	EXTRA_MESSAGE						= "message";
	public final static int		PLAY_SERVICES_RESOLUTION_REQUEST	= 9000;
	public static final String	SENDER_ID							= "793977106476";
	private SharedPreferences	mPrefs;

	private void startApp() {
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				loadingCompleted();
			}
		}, 1000);
	}

	// /////////////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash_screen);
		splash_progressbar = (ProgressBar) findViewById(R.id.splash_progressbar);
		txtStatus = (TextView) findViewById(R.id.splash_txtStatus);
		mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		mPrefs.edit().putInt("FirstStart", 0).commit();
	}

	@Override
	protected void onResume() {
		super.onResume();
		loadingCompleted = false;
		
		if (!Utilities.isNetworkEnabled(getApplicationContext())) {
			new AlertDialog.Builder(this).setTitle(getString(R.string.no_internet_connection))
					.setMessage(getString(R.string.internet_connection_request))
					.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
							startActivity(intent);
						}
					}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}).create().show();
			return;
		}
		if (!checkPlayServices()) {
			finish();
		}
		
		new OneTimeStoreID().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		StartAnimation();
		startApp();

	}

	public void EnableLoadingBar(boolean state) {
		if (state) {
			// splash_imageview.setVisibility(View.INVISIBLE);
			splash_progressbar.setVisibility(View.VISIBLE);
		} else {
			// splash_imageview.setVisibility(View.VISIBLE);
			splash_progressbar.setVisibility(View.INVISIBLE);
		}
	}

	private void StartAnimation() {
		anim = AnimationUtils.loadAnimation(SplashScreen.this, R.anim.fade_splash);
		anim.reset();
		// splash_imageview.clearAnimation();
		// splash_imageview.startAnimation(anim);
	}

	public synchronized void onLoadCompleted() {
		if (loaded)
			return;
		Log.w("SplashScreen", "Start MainActivity");
		loaded = true;
		GetLastData();
		Intent intent = new Intent(SplashScreen.this, MainActivity.class);
		startActivity(intent);
		SplashScreen.this.finish();
	}

	public Member	mUser;

	void GetLastData() {
		Gson gson = new Gson();

		String user = GetPreference("User");
		if (!user.equals("")) {
			mUser = gson.fromJson(user, Member.class);
		}

		String best = GetPreference("ListProductBest");
		if (best.equals("")) {
			new CallServiceTask() {
				private ArrayList<Product>	rs	= new ArrayList<Product>();

				protected void onPreExecute() {
					txtStatus.setText(R.string.firsttime);
				};

				public void work() {
					try {
						if (mUser == null)
							rs = service.getBestOfDay(new Date(), -1);
						else
							rs = service.getBestOfDay(new Date(), mUser.Id);
					} catch (IOException e) {} catch (XmlPullParserException e) {}
				};

				protected void onPostExecute(Void result) {
					if (rs == null)
						return;
					if (rs.size() == 0) {

					} else {
						AddPreference("ListProductBest", ConvertToJson(rs));
					}
				};
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}

	}

	public String GetPreference(String tag) {
		return mPrefs.getString(tag, "");
	}

	public String ConvertToJson(Object O) {
		Gson gson = new Gson();
		return gson.toJson(O);
	}

	public void AddPreference(String tag, String value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putString(tag, value);
		editor.commit();
	}

	public synchronized void loadingCompleted() {
		if (!loadingCompleted) {
			loadingCompleted = true;
			// EnableLoadingBar(true);
		} else
			onLoadCompleted();
	}

	@Override
	public void onBackPressed() {
		new MyDialogHandler().confirm(this, getString(R.string.confirm_exit), getString(R.string.do_you_want_to_exit_), getString(R.string.cancel),
				getString(R.string.ok), new Runnable() {
					@Override
					public void run() {
						finish();
					}
				}, null);
	}

	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.w("GCM", "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

//	private String getRegistrationId(Context context) {
//		final SharedPreferences prefs = getSharedPreferences(Const.MAIN_PREF, Context.MODE_PRIVATE);
//		String registrationId = prefs.getString(Const.PROPERTY_REG_ID, "");
//		if (registrationId.length() == 0) {
//			Log.i("GCM", "Registration not found.");
//			return "";
//		}
//		// Check if app was updated; if so, it must clear the registration ID
//		// since the existing regID is not guaranteed to work with the new
//		// app version.
//		int registeredVersion = prefs.getInt(Const.PROPERTY_APP_VERSION, Integer.MIN_VALUE);
//		int currentVersion = Utilities.getAppVersion(context);
//		if (registeredVersion != currentVersion) {
//			Log.i("GCM", "App version changed.");
//			return "";
//		}
//		return registrationId;
//	}

	/**
	 * Get Device ID and Google Cloud Message ID. If failed, app will exit
	 */
	class OneTimeStoreID extends AsyncTask<Integer, Integer, Boolean> {
		SharedPreferences	pref;
		String				deviceId	= null;
		String				gcmId		= "";

		@Override
		protected void onPreExecute() {
			pref = getApplicationContext().getSharedPreferences(Const.MAIN_PREF, Context.MODE_PRIVATE);
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			deviceId = pref.getString(UNIQUE_DEVICE_ID, null);
			if (deviceId == null || deviceId.equals("")) {
				deviceId = Tracker.getDeviceID(getApplicationContext());
				pref.edit().putString(UNIQUE_DEVICE_ID, deviceId).commit();
			}

			gcmId = Utilities.getRegistrationId(getApplicationContext());
			if (gcmId.equals("")) {
				try {
					Log.w("GCM", "Registering new GCM-ID");
					if (gcm == null)
						gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
					gcmId = gcm.register(SENDER_ID);
					Log.w("GCM", "New GCM-ID" + gcmId);
					Utilities.storeRegistrationId(getApplicationContext(), gcmId);
					int res = new Service().newDeviceID(deviceId, gcmId);
					return (res > 0);
				} catch (IOException ex) {
					ex.printStackTrace();
					return false;
				} catch (XmlPullParserException e) {
					e.printStackTrace();
					return false;
				}
			}

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!result) {
				Log.e("Initialize", "Initialize failed! Now exitting.");
				finish();
			} else {
				Log.w("Initialize", "Initialize success.");
				new AsyncTask<Integer, Integer, Boolean> () {
					@Override
					protected Boolean doInBackground(Integer... params) {
						int rs = 0;
						try {
							PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
							int api = Build.VERSION.SDK_INT;
							Member m = new Gson().fromJson(GetPreference("User"), Member.class);
							String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
							rs = new Service().appOpenTrack(deviceId, pInfo.versionName, api, (m != null) ? m.Email : "", date);
						} catch (Exception e) {
						}
						return rs == 1;
					}
				}.executeOnExecutor(THREAD_POOL_EXECUTOR);
				startApp();
			}
		}
	}
}
